package top.haijunit.cloud.authorization.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import top.haijunit.cloud.authorization.model.Result;
import top.haijunit.cloud.authorization.model.response.CaptchaResult;
import top.haijunit.cloud.authorization.support.RedisOperator;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ThreadLocalRandom;

import static top.haijunit.cloud.authorization.constant.RedisConstants.*;

/**
 * 登录接口，登录使用的接口
 *
 * @author vains
 */
@RestController
@RequiredArgsConstructor
public class LoginController {

    private final RedisOperator<String> redisOperator;

    @GetMapping("/getSmsCaptcha")
    public Result<String> getSmsCaptcha(String phone) {
        // 示例项目，固定1234
        String smsCaptcha = "666999";
        // 存入缓存中，5分钟后过期
        redisOperator.set((SMS_CAPTCHA_PREFIX_KEY + phone), smsCaptcha, DEFAULT_TIMEOUT_SECONDS);
        return Result.success("获取短信验证码成功.", smsCaptcha);
    }

    @GetMapping("/getCaptcha")
    public Result<CaptchaResult> getCaptcha() {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(100, 30, 4, 20);
        lineCaptcha.setGenerator(new RandomGenerator("0123456789", 4));
        // 生成验证码uuid
        String uuid = IdUtil.fastSimpleUUID();
        String code = lineCaptcha.getCode();
        String images = "data:image/jpeg;base64," + lineCaptcha.getImageBase64();
        // 存入缓存中，5分钟后过期
        redisOperator.set((IMAGE_CAPTCHA_PREFIX_KEY + uuid), code, DEFAULT_TIMEOUT_SECONDS);
        return Result.success("获取验证码成功.", new CaptchaResult(uuid, null, images));
    }

}
